package com.base.app.base;

import android.app.Activity;
import android.app.ProgressDialog;
//import android.app.StatusBarManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.base.app.BaseApplication;
import com.base.app.MainActivity;
import com.base.app.util.SpCommon;
//import com.jomoo.mirror.BaseApplication;
//import com.jomoo.mirror.R;
//import com.jomoo.mirror.bean.BleDeviceBean;
//import com.jomoo.mirror.controller.AllBleDeviceController;
//import com.jomoo.mirror.page.MainActivity;
//import com.jomoo.mirror.service.BleService;
//import com.jomoo.mirror.service.CastService;
//import com.jomoo.mirror.util.ScreenManager;
//import com.jomoo.mirror.util.ScreenOffAdminReceiver;
//import com.jomoo.mirror.util.SpCommon;
//import com.jomoo.mirror.util.WifiUtils;
//import com.jomoo.mirror.view.UnifyProgressDialog;
//import com.zhy.http.okhttp.utils.L;

import java.util.LinkedList;
import java.util.List;

public abstract class BaseActivity extends AppCompatActivity {
    final String TAG = BaseActivity.class.getSimpleName();
    protected final String INTENT_SCREENSAVER_ON = "INTENT_SCREENSAVER_ON";
    BaseActivity mTopActivity;
    private List<BaseActivity> activitys = new LinkedList<BaseActivity>();
    private long mPreClickTime;
    private ProgressDialog progressDialog;

    protected boolean isOnTop = false;
    public boolean isShowKeyBoard;

    public SpCommon spCommon;
    public final int SCREEN_BRIGHTNESS_NONE = -1000;
    public int screenBrightness=SCREEN_BRIGHTNESS_NONE;
//    private GestureDetector mDetector;

    View statusBarview;
    WindowManager manager;

    private GestureDetector gestureDetector;

    private static long lastClickTime;
    private static boolean firstClick = true;
    MotionEvent firstEvent;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 200) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public BaseActivity getTopActivity() {
        return mTopActivity;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置全屏
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        View decorView = getWindow().getDecorView();
//        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
//                View.SYSTEM_UI_FLAG_FULLSCREEN;
//        decorView.setSystemUiVisibility(uiOptions);
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_IMMERSIVE
//                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                | View.SYSTEM_UI_FLAG_FULLSCREEN
//        );
        // 设置全屏模式并隐藏状态栏
        makeWindowFullScreen();

//        StatusBarUtil.disableStatusBar(this);

        setContentView(setViewId());
        initSP();
        beforeInitView();
        initView();
        initData();
        initListener();

        //是否网络连接
//        if(!WifiUtils.isWifiConnected(this)){
//            Toast.makeText(this, "Wifi网络连接异常", Toast.LENGTH_SHORT).show();
//        }

        gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                Log.e(TAG, "单击事件");
                return super.onDown(e);
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                // 在这里处理双击事件
                // 返回true表明事件被处理了
                Log.e(TAG, "双击事件");
//                Toast.makeText(BaseActivity.this, "双击", Toast.LENGTH_SHORT).show();
                return true;
            }

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Log.e(TAG, "单击事件");
                return false;
            }
        });


//        registerScreensaverBroadcast();
    }

    /**
     * activity启动时调用禁止下拉
     */
    private void prohibitDropDown() {
        manager = ((WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE));
        WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
        localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
        localLayoutParams.gravity = Gravity.TOP;
        localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                // this is to enable the notification to recieve touch events
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                // Draws over status bar
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        localLayoutParams.height = (int) (30 * getResources()
                .getDisplayMetrics().scaledDensity);
        localLayoutParams.format = PixelFormat.TRANSPARENT;
        manager.addView(statusBarview, localLayoutParams);
    }


    /**
     * activity销毁时允许下拉，不然程序不大退，怎么都无法下拉状态栏
     */
    private void allowDropDown() {
        manager.removeView(statusBarview);
    }

    //在Ui中调用此函数，确保满屏隐藏虚拟键盘
    public void makeWindowFullScreen() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        );
    }

    private void initSP(){
        spCommon = BaseApplication.getSpCommon();
    }

    private void initScreenBrightness(){
//        screenBrightness = spCommon.getInt(SpCommon.SCREEN_BRIGHTNESS_VALUE, SCREEN_BRIGHTNESS_NONE);
////        Log.e(TAG, "screenBrightness = " + screenBrightness);
//        if(screenBrightness == SCREEN_BRIGHTNESS_NONE) {
//            screenBrightness = 100;
//            Log.e(TAG, "设置屏幕亮度：" + screenBrightness);
//            spCommon.putInt(SpCommon.SCREEN_BRIGHTNESS_VALUE, screenBrightness);
//            changeAppBrightness(this, screenBrightness/100f);
//        }else{
//            changeAppBrightness(this, screenBrightness/100f);
//        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        boolean doubleEvent = gestureDetector.onTouchEvent(ev);
        if(!doubleEvent) {
        }else{
//            Log.e(TAG, "触摸面积：" + ev.getSize());
            screenOff(this,this);
        }
        return super.onTouchEvent(ev);
    }

    public void screenOff(Context context, Activity activity) {
//        DevicePolicyManager policyManager = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
//        ComponentName adminReceiver = new ComponentName(context, ScreenOffAdminReceiver.class);
//        boolean admin = policyManager.isAdminActive(adminReceiver);
//        boolean screenSaverEnable = spCommon.getBoolean(SpCommon.SCREENSAVER_SWITCH_ENABLE);
//        if (admin) {
//            if(screenSaverEnable) {
//                showScreensaver();//屏保
//            }else{
//                policyManager.lockNow();//息屏
//            }
//        } else {
//            Toast.makeText(context, "没有设备管理权限", Toast.LENGTH_LONG).show();
//            //TODO test 显示屏保
////            showScreensaver();
//        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isOnTop = true;
        mTopActivity = this;
        activitys.add(this);
        initScreenBrightness();

        //启动投屏服务，即使多次start，系统只会创建一个Service实例，但是注意Service的onStart()方法会被调用多次
//        startCastService();

        //
//        Settings.System.putInt(getContentResolver(), "status_bar_disabled", 1);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isOnTop = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unregisterScreensaverBroadcast();
        activitys.remove(this);
    }

    protected abstract int setViewId();

    protected abstract void beforeInitView();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void initListener();

    public List<BaseActivity> getActivitys() {
        return activitys;
    }

    /**
     * 完全退出
     */
    public void exit() {
        for (BaseActivity baseActivity : activitys) {
            baseActivity.finish();
        }
    }

    @Override
    public void onBackPressed() {
        if (this instanceof MainActivity) {// 主页
            if (System.currentTimeMillis() - mPreClickTime > 2000) {// 两次点击的间隔大于2s中
                Toast.makeText(getApplicationContext(), "再按一次,退出", Toast.LENGTH_SHORT).show();
                mPreClickTime = System.currentTimeMillis();
            } else {
                exit();
            }
        } else {
            super.onBackPressed();// finish
        }
    }

    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    //获取当前activity的名字
    public String getRunningActivityName() {
        String contextString = this.toString();
        return contextString.substring(contextString.lastIndexOf(".") + 1, contextString.indexOf("@"));
    }

    public void hideSoftInput() {
        if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (manager != null) {
                isShowKeyBoard = !manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            }
        }
    }

    public void changeAppBrightness(Context context, float brightness) {
        Window window = ((Activity) context).getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = brightness <= 0 ? 0.06f : brightness;//(brightness <= 0 ? 1 : brightness) / 255f;
        }
        window.setAttributes(lp);
    }

    public int getNowBrightnessIndex() {
        return screenBrightness;
    }

//    private void registerScreensaverBroadcast(){
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(AllBleDeviceController.SCREENSAVER_STATE_BC);
//        registerReceiver(screensaverBroadcastReceiver, intentFilter);
//    }
//    private void unregisterScreensaverBroadcast(){
//        unregisterReceiver(screensaverBroadcastReceiver);
//    }
//    private BroadcastReceiver screensaverBroadcastReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            try {
//                if (intent != null && intent.hasExtra(AllBleDeviceController.DATA_TYPE)) {
//                    int state = intent.getIntExtra(AllBleDeviceController.DATA_TYPE, -1);
//                    Bundle bundle = intent.getExtras();
//                    switch (state) {
//                        case AllBleDeviceController.STATE_SCREENSAVER_SWITCH_OFF:
//                            break;
//                        case AllBleDeviceController.STATE_SCREENSAVER_SWITCH_ON:
//                            Log.e(TAG, "屏保强制开启MainActivity");
//                            beforeStartScreensaver();
//                            showScreensaver();
//                            break;
//                    }
//                }
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }
//    };

    private void showScreensaver(){
        Intent intent1 = new Intent(BaseActivity.this, MainActivity.class);
        intent1.putExtra(INTENT_SCREENSAVER_ON, true);
        startActivity(intent1);
    }

    public void beforeStartScreensaver(){

    }
}
